package com.qiguliuxing.dts.wx.annotation.support;

import com.alibaba.fastjson.JSON;
import com.qiguliuxing.dts.core.exception.UtilException;
import com.qiguliuxing.dts.wx.util.CacheRequestBodyWrapper;
import com.qiguliuxing.dts.wx.util.IllegalStrFilterUtil;
import com.qiguliuxing.dts.wx.util.ServletUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;

/**
 * @author Hva
 * @Description: Request Body 缓存 Filter，实现它的可重复读取
 */
public class CacheRequestBodyFilter extends OncePerRequestFilter {
    private static final Logger logger = LoggerFactory.getLogger(CacheRequestBodyFilter.class);

    @Override
    protected void doFilterInternal(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, FilterChain filterChain)
            throws IOException, ServletException {
        CacheRequestBodyWrapper bodyWrapper = new CacheRequestBodyWrapper(request);
        BufferedReader streamReader = new BufferedReader(new InputStreamReader(bodyWrapper.getInputStream(), "UTF-8"));
        StringBuilder responseStrBuilder = new StringBuilder();
        String inputStr;
        while ((inputStr = streamReader.readLine()) != null)
            responseStrBuilder.append(inputStr);
        String string = responseStrBuilder.toString();
        Map<String, String[]> parameterMap = request.getParameterMap();
        String rest = JSON.toJSONString(parameterMap);
        logger.info("doFilterInternal请求参数:{}",string + rest);
        Boolean filter = IllegalStrFilterUtil.sqlStrFilter(string + rest);
        logger.info("doFilterInternal结果:{}",filter);
        if(filter){
            filterChain.doFilter(bodyWrapper, response);
        }else{
            throw new UtilException("参数中包含特殊字符");
        }

    }
 
    @Override
    protected boolean shouldNotFilter(@NotNull HttpServletRequest request) {
        // 只处理 json 请求内容
        return !ServletUtils.isJsonRequest(request);
    }
}